package com.pqtest.api.service;

import com.alibaba.fastjson.JSONObject;
import com.pqtest.api.dto.JwtDto;
import com.pqtest.api.properties.JwtProperties;
import io.jsonwebtoken.Jwts;
import io.netty.handler.codec.base64.Base64Decoder;
import lombok.extern.java.Log;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import sun.misc.BASE64Decoder;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Service
@Log
public class JwtService {
    @Autowired
    private JwtProperties jwtProperties;
    public JwtDto getUser(OAuth2Authentication oAuth2Authentication) throws IOException {
        String uname = (String)oAuth2Authentication.getUserAuthentication().getPrincipal();
        String[] su = uname.split("_");
        JwtDto jwtDto = new JwtDto();
        jwtDto.setId(su[0]);
        jwtDto.setName(su[1]);
//        HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
//        String token = req.getHeader("Authorization").split(" ")[1];
//        String claim = token.split("\\.")[1];
//        log.info(token);
//        Object user = Jwts.parser().setSigningKey(generalKey()).parseClaimsJws(token).getBody();
//        log.info(user.toString());
//        BASE64Decoder decoder = new BASE64Decoder();
//        byte[] d = decoder.decodeBuffer(claim);
//        String ds = new String(d,"UTF-8");
//        log.info(ds);
//        JSONObject o = JSONObject.parseObject(ds);
//        log.info(o.getString("user_name"));
          return jwtDto;
    }
//    /**
//     * 由字符串生成加密key
//     * @return
//     */
//    public SecretKey generalKey(){
//        String stringKey = "e9e81816872ed889f4de9a04661ea98a";//本地配置文件中加密的密文7786df7fc3a34e26a61c034d5ec8245d
//        byte[] encodedKey = Base64.decodeBase64(stringKey);//本地的密码解码[B@152f6e2
//        System.out.println(encodedKey);//[B@152f6e2
//        System.out.println(Base64.encodeBase64URLSafeString(encodedKey));//7786df7fc3a34e26a61c034d5ec8245d
//        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");// 根据给定的字节数组使用AES加密算法构造一个密钥，使用 encodedKey中的始于且包含 0 到前 leng 个字节这是当然是所有。（后面的文章中马上回推出讲解Java加密和解密的一些算法）
//        return key;
//    }
}
